import { asyncRoutes, basicRoutes } from '@/router'

// 权限过滤条件
function hasPermission(routeMap, routeItem) {
  const Perms = routeMap[routeItem.name] ?? []
  return Perms?.some(item => item?.Name.includes?.('query')) || routeItem.noPerm
}

// 根据权限筛选路由
export function filterAsyncRoutes(routeMap, routeList) {
  routeList.forEach(item => {
    if (item?.children?.length) {
      item.children = item.children.filter(childItem => hasPermission(routeMap, childItem))
    }
  })
  routeList = routeList.filter(
    rootItem => rootItem?.children?.length || hasPermission(routeMap, rootItem),
  )

  return routeList
}

// state
const state = {
  routes: [],
  addRoutes: [],
}

// getters
const getters = {
  routes: state => state.routes,
  addRoutes: state => state.addRoutes,
}

// mutations
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = basicRoutes.concat(routes)
  },
}

// actions
const actions = {
  generateRoutes({ commit }, permMap) {
    return new Promise(resolve => {
      const accessedRoutes = permMap ? filterAsyncRoutes(permMap, asyncRoutes) : asyncRoutes
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
}
